import * as THREE from "three";
import { colors, indices } from "../utils/index";

export const drawCube = (points, type, option, materials) => {
  const pointArr = points.map((e) => [e.x, e.y, e.z]).flat();
  const vertices = new Float32Array(pointArr);

  const geometry = new THREE.BufferGeometry();
  geometry.setAttribute("position", new THREE.BufferAttribute(vertices, 3));
  geometry.setIndex(indices);
  geometry.computeVertexNormals(); // 计算法线，确保光照正常

  const uvs = new Float32Array([
    // 前面
    0, 1, 1, 1, 1, 0, 0, 0,  // 前面 0,6
    // 后面
    0, 1, 1, 1, 1, 0, 0, 0,  // 后面 6,6
    // 左面
    0, 0, 0, 1, 0, 0, 0, 1,  // 左面 12,6
    // 右面
    0, 1, 1, 1, 1, 0, 0, 0,  // 右面 18,6
    // 底面
    0, 1, 1, 1, 1, 0, 0, 0,  // 底面 24,6
    // 顶面
    0, 1, 1, 1, 1, 0, 0, 0,   // 顶面 30,6
  ]);
  //设置UV
  geometry.setAttribute('uv', new THREE.BufferAttribute(uvs, 2));

  const count = 6
  for (let index = 0; index < 6; index++) {
    geometry.addGroup(index * count, count, index)
  }

  // geometry.setDrawRange(12,6)

  const material = new THREE.MeshStandardMaterial({
    color: colors[type],
    side: THREE.DoubleSide,
  });

  // 创建立方体
  const cube = new THREE.Mesh(geometry, materials);
  cube.castShadow = true;
  cube.userData = option;

  console.log(cube.geometry)
  return cube;
};
